from openai import OpenAI
import json
import os
import base64
import re
import requests
from urllib.parse import urlparse

os.environ["OPENAI_API_KEY"] = "sk-XvscnLu7HUR62QtquoqZVHRvrqNdHgvKFeZ3KYnKbqjn8KrU"
os.environ["OPENAI_API_BASE"] = "https://api-ai-us.pingpongx.org/v1"
client = OpenAI(
    api_key="sk-XvscnLu7HUR62QtquoqZVHRvrqNdHgvKFeZ3KYnKbqjn8KrU",
    base_url="https://api-ai-us.pingpongx.org/v1",
)

client_cn = OpenAI(
    api_key="sk-XvscnLu7HUR62QtquoqZVHRvrqNdHgvKFeZ3KYnKbqjn8KrU",
    base_url="https://api-ai-cn.pingpongx.com/v1",
)


def get_json_string(page_content):
    msg = [
        {
            "role": "system",
            "content": """帮我提取出文本中的json，注意只需要json部分，不需要其他的说明。
        """,
        },
        {
            "role": "user",
            "content": page_content,
        },
    ]
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=msg,
        response_format={"type": "json_object"},
        temperature=0,
    )
    res_cont = response.choices[0].message.content
    # print(res_cont)
    res_json = json.loads(res_cont)
    return res_cont, res_json


def get_title_description(page_content):
    msg = [
        {
            "role": "system",
            "content": """你是一论文阅读工具，请根据下面的描述提取论文中的相关信息。
        请从论文第一页提取论文标题、论文的主要思想以及主要作者所属机构、公司或者学校(为了脱敏请忽略人名)，输出成json格式，
        并翻译成中文：
        论文的主要思想控制在100字以内。
        ```
        格式如下
       {"title": "", "main_desciption": "", "title_ch": "", "main_desciption_ch": "", "author": ""}
        """,
        },
        {
            "role": "user",
            "content": page_content,
        },
    ]
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=msg,
        response_format={"type": "json_object"},
        temperature=0,
    )
    res_cont = response.choices[0].message.content
    print(res_cont)
    res_json = json.loads(res_cont)
    return res_cont, res_json


def detect_image_rotation(image_input):
    """判断图片的旋转角度

    Args:
        image_input (str): 图片本地路径或URL地址

    Returns:
        tuple: (str, int) - (API响应内容, 旋转角度[0,90,180,270])
    """

    def is_url(string):
        try:
            result = urlparse(string)
            return all([result.scheme, result.netloc])
        except:
            return False

    # 处理图片输入
    if is_url(image_input):
        # 如果是URL，直接使用
        image_url = image_input
    else:
        # 如果是本地文件，转换为base64
        try:
            with open(image_input, "rb") as image_file:
                encoded_image = base64.b64encode(image_file.read()).decode("utf-8")
                image_url = f"data:image/jpeg;base64,{encoded_image}"
        except Exception as e:
            raise Exception(f"无法读取图片文件: {str(e)}")

    msg = [
        {
            "role": "system",
            "content": """You are an image analysis tool.
        Please analyze if the image has been rotated counterclockwise from its normal orientation.
        If the image is too complex to determine or is already in the correct orientation, return 0.
        Output format should be JSON: {"rotation": angle value}""",
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
                {
                    "type": "text",
                    "text": "Please only return one of these values: 0, 90, 180, or 270.",
                },
            ],
        },
    ]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=msg,
        response_format={"type": "json_object"},
        temperature=0,
        max_tokens=100,
    )

    res_cont = response.choices[0].message.content
    res_json = json.loads(res_cont)
    return res_cont, res_json["rotation"]


def reg_pic_type(image_input):
    def is_url(string):
        try:
            result = urlparse(string)
            return all([result.scheme, result.netloc])
        except:
            return False

    # 处理图片输入
    if is_url(image_input):
        # 如果是URL，直接使用
        image_url = image_input
    else:
        # 如果是本地文件，转换为base64
        try:
            with open(image_input, "rb") as image_file:
                encoded_image = base64.b64encode(image_file.read()).decode("utf-8")
                image_url = f"data:image/jpeg;base64,{encoded_image}"
        except Exception as e:
            raise Exception(f"无法读取图片文件: {str(e)}")

    msg = [
        {
            "role": "system",
            "content": """You are an image analysis tool.
            请分析图片是证件的正面还是反面，正面是表示有人像的一面，反面是有指纹的一面。
            正面返回1，反面返回2，无法判断返回0，请输出json格式
            
            返回的格式：
            {"pic_type": 1, "reason": "有人脸信息"}
            """,
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
                {
                    "type": "text",
                    "text": "请输出结果为json格式，包含pic_type和reason字段",
                },
            ],
        },
    ]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=msg,
        response_format={"type": "json_object"},
        temperature=0,
        max_tokens=100,
    )

    res_cont = response.choices[0].message.content
    res_json = json.loads(res_cont)
    return res_cont, res_json["pic_type"]


if __name__ == "__main__":
    # get_title_description("nihao ")
    # res = detect_image_rotation(
    #     "/data_ext/gradio_model_mix/chat_arena/data/viet_id_card_val/META912406020276132698_2.jpg"
    # )
    # print(res)
    res, pic_type = reg_pic_type(
        "https://flwm-pai.oss-cn-hangzhou.aliyuncs.com/oular/tiktok_scripts/20250714160608_6050.jpg"
    )
    print(res, pic_type)
